import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/flame.dart';
import 'package:flutter/material.dart';
import 'package:freedom/page/mahjong/event/room_inf_update.dart';
import '../bloc/room_info.dart';
import '../common/mahjong_context.dart';

/**
 * 剩余的牌
 */

class ResidueCard extends PositionComponent {
  var winCard = Flame.images.fromCache('mahjong/commons/card_tips.png');
  RoomInfo? _roomInfo;
  ResidueCard(this._roomInfo)
      : super(
            size: Vector2(MahjongContext().centerDiskHeight,
                MahjongContext().centerDiskHeight),
            position: Vector2(
                MahjongContext().diskDirectionPoint.x +
                    MahjongContext().centerDiskHeight * 1.5,
                MahjongContext().diskDirectionPoint.y));

  @override
  FutureOr<void> onLoad() {
    MahjongContext.registerRoomFunc<RoomInfoUpdateEvent>((event) {
      _roomInfo = event.roomInfo;
    });
  }

  void cardeDel() {
    _roomInfo?.gameInfo.residue--;
  }

  @override
  void render(Canvas canvas) {
    double cardHeight = size.y / 3;
    var paint = Paint()
      ..color = Color(0x818181BD)
      ..style = PaintingStyle.fill;
    canvas.drawRect(
        Rect.fromLTWH(0, cardHeight * 2, size.x, cardHeight), paint);
    var textStyle =
        TextStyle(color: Colors.white, fontSize: cardHeight, height: 1.0);

    Sprite(winCard).render(canvas,
        size:
            Vector2(cardHeight / MahjongContext().cardTipsWHRatio, cardHeight),
        position: Vector2(0, cardHeight * 2));
    var textSpan = TextSpan(
        text: _roomInfo?.gameInfo.residue.toString(), style: textStyle);
    var residueCardPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    );
    residueCardPainter.layout();
    residueCardPainter.paint(
        canvas,
        Offset(
            (size.x -
                        cardHeight / MahjongContext().cardTipsWHRatio -
                        residueCardPainter.width) /
                    2 +
                cardHeight / MahjongContext().cardTipsWHRatio,
            size.y - residueCardPainter.height));

    canvas.drawRRect(
        RRect.fromLTRBR(0, 0, size.x, cardHeight, Radius.circular(cardHeight)),
        paint);

    var playingSpan = TextSpan(
        text: "${_roomInfo?.severalInning}/${_roomInfo?.rule?.numberGame}",
        style: TextStyle(
            color: Color.fromARGB(255, 228, 217, 217),
            fontSize: cardHeight,
            height: 1.0));
    var playingPainter = TextPainter(
      text: playingSpan,
      textDirection: TextDirection.ltr,
    );
    playingPainter.layout();
    playingPainter.paint(
        canvas, Offset((size.x - playingPainter.width) / 2, 0));
  }
}
